package kin.dao.system;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.commons.lang.reflect.MethodUtils;
import org.springframework.stereotype.Component;

import kin.bean.system.MyEnumType;
import kin.json.JsonUtils;
import kin.manager.system.XtypeManager;
import kin.system.util.ApplicationContextHelper;
import kin.system.util.StringUtil;

public class XtypeManagerIMP implements XtypeManager{

	public StringBuilder list(String label, String name, String parentClassName,
			String currentClassName,int pid) {
		StringBuilder result = new StringBuilder();
		result.append("{");
		// ApplicationContextHelper.getBean(currentClassName);
		// AM.store.StoreFactory.getStoreByName("AM.store."+className,url,method);
		result.append("xtype:'list',pid:" + pid + ",title:'"+label+"'"+"name:'" + name
				+ "',columns:AM.columns.ColumnsFactory.getColumnsByName('"
				+ currentClassName
				+ "'),store: AM.store.StoreFactory.getStoreByName('AM.store."
				+ currentClassName + "','/"
				+ StringUtil.fristLetterLowerCase(currentClassName) + "/list"
				+ "','GET',parentClass:'"
				+ StringUtil.fristLetterLowerCase(parentClassName) + "')");
		result.append("}");
		return result;

	}

	public  StringBuilder treecombo(String label,String name, boolean editor,
			 String comboName, String targetClass) {
		StringBuilder result = new StringBuilder();
		StringBuilder list = new StringBuilder();
		Object obj = ApplicationContextHelper.getBean(StringUtil
				.fristLetterLowerCase(targetClass) + "ServiceManagerIMP");
		/*
		 * StandardEvaluationContext context = new
		 * StandardEvaluationContext(obj); ExpressionParser parser = new
		 * SpelExpressionParser(); List l=(List)
		 * parser.parseExpression("findAll()").getValue(context);
		 */
		List l = null;
		try {
			l = (List) MethodUtils.invokeMethod(obj, "findAll", null);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (l != null && l.size() > 0) {
			list.append("[");

			for (Object o : l) {

				list.append(JsonUtils.jsonFromObject(o) + ",");

			}
			StringUtil.deleteLastSymbol(list, ",");
			list.append("]");

		}
		result.append("{");
		result.append("xtype:'treecombo',fieldLabel:'"
				+ label
				+ "',name:'"
				+ name
				+ "',displayField: '"
				+ comboName
				+ "',valueField: '"
				+ StringUtil.fristLetterLowerCase(targetClass)
				+ "_id',selectChildren: false,canSelectFolders: true,rootVisible:false,store: ");
		result.append("Ext.create('Ext.data.TreeStore', {fields:['"
				+ StringUtil.fristLetterLowerCase(targetClass)
				+ "_id','"
				+ comboName
				+ "'],  root: { name: 'Root',expanded: true, children: [{goodsCategory_id: '1',name: 'First node',leaf: false,children: [{goodsCategory_id: '3',name: 'First child node', leaf: true},{goodsCategory_id: '4', name: 'Second child node',leaf: true}] },{ goodsCategory_id: '2',name: 'Second node',leaf: true }]},folderSort: false})");
		result.append("}");
		System.out.println("tree:" + list);
		return result;

	}

	public StringBuilder boxselect(int pid, String parentClassName,
			String currentClassName) {
		StringBuilder result = new StringBuilder();
		
		return null;

	}

	public  StringBuilder combo(String label,String fieldName, boolean allowBlank,
			int sort, boolean iscolumn, boolean editable, 
			boolean isEnum, String targetName, String comboName,
			String cascadeTarget, LinkedHashMap<String, Object> targetWhere,
			LinkedHashMap<String, Object> CastCaseTargetWhere) {
		StringBuilder result = new StringBuilder();
		/*
		 * if(isEnum){ targetName=targetName.substring(0,
		 * targetName.lastIndexOf("_")); }
		 */
		result.append("{xtype: 'combo',typeAhead: true,");
		if (0 != sort) {
			result.append("sort:" + sort + ",");
		}
		result.append("allowBlank:" + allowBlank + ",");
		if (allowBlank != true) {
			result.append("blankText:'" + label + "不能为空',");
		}

		if (label != null && label != "") {
			result.append("fieldLabel :'" + label + "',");
		}
		result.append("triggerAction: 'all',"
				+ "selectOnTab: true,"
				+ "lazyRender: true,"
				+ "editable:false,"
				+ "listConfig: {minWidth: 70, maxHeight: 300,shadow: 'sides',loadMask:false},"

				+ "name: '" + fieldName + "',");

		result.append("displayField: '"
				+ /* comboName!=null?comboName: */StringUtil
						.fristLetterLowerCase(targetName) + "_name"
				/*
				 * StringUtil.fristLetterLowerCase(targetName) + "_name"
				 */
				+ "'," + "valueField: '"
				+ StringUtil.fristLetterLowerCase(targetName) + "_id" + "',"
				+ "emptyText : '请选择',");
		// if(null!=cascadeTarget&&!"".equals(cascadeTarget)){
		/*
		 * result.append("listeners: {'change': function (com, value, options,a,b){"
		 * +
		 * 
		 * "console.dir(com);"+ "console.dir(value);"+ "console.dir(options);"+
		 * "console.dir(a);"+ "console.dir(b);"+
		 * 
		 * "}},");
		 */
		// }

		result.append("store: new Ext.data.Store({storeId:'local"
				+ StringUtil.fristLetterLowerCase(targetName)
				+ "',autoLoad:true,");
		result.append("data : [");
		if (isEnum) {
			// targetName=targetName.substring(0, endIndex)

			for (MyEnumType met : MyEnumType.values()) {
				if (met.name().startsWith(targetName)) {
					result.append("{");
					result.append(StringUtil.fristLetterLowerCase(targetName)
							+ "_name" + ":'" + met.getMyEnumType_name() + "',"
							+ StringUtil.fristLetterLowerCase(targetName)
							+ "_id" + ":" + met.ordinal());
					result.append("},");
				}
			}
			if (result.length() - 1 == result.lastIndexOf(",")) {
				result.deleteCharAt(result.length() - 1);
			}

		} else {
			
			try {
				Object o = ApplicationContextHelper.getBean(StringUtil
				.fristLetterLowerCase(targetName) + "ServiceManagerIMP");
				if(o==null){
				Class cl=Class.forName("kin.dao.customer."+StringUtil.fristLetterUpperCase(targetName)+"ManagerIMP");
	          o=cl.newInstance();
				}
				Method method;
				method = o.getClass().getMethod(
						"findList",
						new Class[] { LinkedHashMap.class, LinkedHashMap.class,LinkedHashMap.class,LinkedHashMap.class });

				List l = (List) method.invoke(o, null, null, null, null);
				for (Object obj : l) {
					Method name = obj.getClass().getMethod(

					"get" + StringUtil.fristLetterUpperCase(comboName),
					// "get" + targetName + "_name",
							new Class[] {});
					String s_name = (String) name.invoke(obj, null);
					Method getId = obj.getClass().getMethod(
							"get" + targetName + "_id", new Class[] {});
					int s_id = (Integer) getId.invoke(obj, null);
					result.append("{" + comboName + ":'"/*
														 * StringUtil.
														 * fristLetterLowerCase
														 * (targetName
														 * )+"_name:'"
														 */+ s_name + "',"
							+ StringUtil.fristLetterLowerCase(targetName)
							+ "_id:" + s_id + "},");
				}
				if (result.length() - 1 == result.lastIndexOf(",")) {
					result.deleteCharAt(result.length() - 1);
				}
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		result.append("],");
		result.append("fields: ['"
				+ StringUtil.fristLetterLowerCase(targetName)
				+ "_id"
				+ "','"
				+ StringUtil.fristLetterLowerCase(comboName != null ? comboName
						: targetName + "_name")

				+ "']})");
		if (iscolumn) {
			result.append("}");
		}
		result.append(",");

		result.append("renderer: function(val){"
				+ "var y=Ext.data.StoreManager.lookup('"
				+ "local"
				+ StringUtil.fristLetterLowerCase(targetName)
				+ "');"
				+ "var index = y.findExact('"
				+ StringUtil.fristLetterLowerCase(targetName)
				+ "_id"
				+ "',val);"
				+ " if (index != -1){"
				+ " var rs = y.getAt(index).data; "
				+ "  return rs."
				+ StringUtil.fristLetterLowerCase(comboName != null ? comboName
						: targetName + "_name") + ";" + "}" + " return  "
				+ "val;" +

				"}");
		if (!iscolumn) {
			result.append("}");
		}

		return result;

	}

	public  StringBuilder textfield(String label,String name,int minLength, int maxLength,
			boolean allowBlank, String vtype, int sort, 
			 boolean hidden) {
		StringBuilder result = new StringBuilder();
		result.append("{");
		result.append("xtype:'textfield',");
		if (0 != sort) {
			result.append("sort:" + sort + ",");
		}
		result.append("allowBlank:" + allowBlank + ",");

		if (allowBlank != true) {
			result.append("blankText:'" + label + "不能为空',");
		}
		if (vtype != "") {
			result.append("vtype:'" + vtype + "',");
		}
		if (0 < minLength) {
			result.append("minText:'最小长度不能少于" + minLength + "',");
			result.append("maxLength:" + maxLength + ",");
		}
		if (0 < maxLength) {
			result.append("minText:'最大长度不能大于" + maxLength + "',");
			result.append("minLength:" + minLength + ",");
		}

		result.append("name:'" + name + "',hidden:" + hidden);
		if (label != null && label != null) {
			result.append(",fieldLabel: '" + label + "'");
		}
		result.append("}");
		return result;

	}

	public StringBuilder ckeditorfield(String label,
			 String name,boolean allowBlank, int sort) {
		StringBuilder result = new StringBuilder();
		result.append("{xtype: 'ckeditorfield',name:'" + name + "',");
		result.append("allowBlank:" + allowBlank);
		if (allowBlank != true) {
			result.append(",blankText:'" + label + "不能为空'");
		}
		if (0 != sort) {
			result.append(",sort:" + sort + "");
		}

		// "anchor: '100%',"+

		/*
		 * "keyNavEnabled: false,"+ "mouseWheelEnabled: false,"+
		 */

		// minValue: 0, //prevents negative numbers

		// Remove spinner buttons, and arrow key and mouse wheel listeners

		if (!"".equals(label) && null != label) {
			result.append(",fieldLabel:'" + label + "'");
		}
		result.append("}");
		return result;
	}

	public StringBuilder datefield(String label, String name,boolean allowBlank,
			int sort, String format,  boolean hidden,boolean isColumn) {
		StringBuilder result = new StringBuilder();
		result.append("{xtype:'datefield',hidden:" + hidden + ",");
		result.append("allowBlank:" + allowBlank);
		if (allowBlank != true) {
			result.append(",blankText:'" + label + "不能为空'");
		}
		if (0 != sort) {
			result.append(",sort:" + sort + "");
		}
		/*
		 * if(""!=name&&null!=name){
		 * 
		 * result.append(",name:"+name+"'"); }
		 */

		result.append(",format:'" + format + "'");
		if (label != null && label != "") {
			result.append(",fieldLabel:'" + label + "'");
		}
		if (isColumn == false) {
			result.append(",name:'" + name + "'");
			result.append(",renderer:function(value){return value ? Ext.Date.dateFormat(value,'"
					+ format + "'):'';}");
		}
		result.append("}");
		return result;

	}

	public StringBuilder checkbox(String label,String name,int sort,  boolean hidden) {
		StringBuilder result = new StringBuilder();
		result.append("{xtype:'checkbox',hidden:" + hidden);
		if (0 != sort) {
			result.append(",sort:" + sort + "");
		}
		/* result.append("checked:'"+checked+"'"); */
		if (label != null && label != "") {
			result.append(",fieldLabel:'" + label + "'");
		}

		result.append("}");

		return result;
	}

	public StringBuilder numberfield(String label, String name,boolean allowBlank, long min,
			long max, int sort,  boolean hidden) {
		StringBuilder result = new StringBuilder();
		{
			result.append("{xtype: 'numberfield'," +
			// "anchor: '100%',"+
					"name: '" + name + "'," +
					/*
					 * "keyNavEnabled: false,"+ "mouseWheelEnabled: false,"+
					 */

					// minValue: 0, //prevents negative numbers

					// Remove spinner buttons, and arrow key and mouse wheel
					// listeners
					"hidden:" + hidden + ",");
			result.append("allowBlank:" + allowBlank);
			if (allowBlank != true) {
				result.append(",blankText:'" + label + "不能为空'");
			}

			if (0 < min) {
				result.append(",minText:'最小值不能少于" + min + "'");
				result.append(",min:" + min);
			}
			if (0 < max) {
				result.append(",maxText:'最大值不能大于" + max + "'");
				result.append(",max:" + max);
			}
			if (0 != sort) {
				result.append(",sort:" + sort + "");
			}
			if (!"".equals(label) && null != label) {
				result.append(",fieldLabel:'" + label + "'");
			}
			result.append("}");
		}
		return result;

	}

	public StringBuilder checkboxgroup() {
		StringBuilder result = new StringBuilder();

		return null;

	}

	public String test(String aaa) {
		// StringBuilder result = new StringBuilder();

		return aaa;

	}

	public StringBuilder button(String label, String action, String url,String targetName, String method) {
		StringBuilder result = new StringBuilder();
		result.append("{xtype : 'button',text:'" + label + "',action:'"
				+ action + "',actionUrl:'" + url + "'," + "targetName:'"
				+ targetName + "',method:'" + method + "'");
		if (action.equals("delete") || action.equals("update")) {
			result.append(",disabled:true");
		}
		result.append("},");

		return result;
	}

	public StringBuilder actioncolumn(String[] item) {
		StringBuilder result = new StringBuilder();

		return result;

	}

}
